package com.hourses.controller;

import com.hourses.page.Page;
import com.hourses.pojo.*;
import com.hourses.service.ProductService;
import com.hourses.service.impl.*;
import com.hourses.utils.TokenUtils;
import com.hourses.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.ReturnedType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.management.relation.RelationSupport;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/5/1 17:35
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    //查询仓库列表  http://localhost:3000/api/product/store-list
    @Autowired
    private StoreServiceImpl storeService;
    @GetMapping("/store-list")
    public Result storeList(){
        Result result = storeService.selectAllStores();
        return result;
    }


    //分页查询商品列表的功能  http://localhost:3000/api/product/product-page-list
    //请求参数：
    //product_table
    //                      productName
    //                      upDownState
    //                      isOverDate
    //                      storeId=1
    //brand_table
    //                      brandName
    //product_type_table
    //                      typeName
    //supply_table
    //                      supplyName
    //place_table
    //                      placeName
    //
    //                      pageSize
    //                      pageNum
    //                      totalNum=0

    //实现分页查询商品列表
    @Autowired
    private ProductServiceImpl productService;
    @GetMapping("/product-page-list")
    public Result selectProductPageList(Product product, Page page){
        //step1:先查询出满足条件的商品总数
        Integer count = productService.selectProductPageList(product);
        page.setTotalNum(count);
        //step2:查询出每一页需要展示的商品列表
        List<Product> products = productService.selectChildList(product, page);
        page.setResultList(products);
        return Result.ok(page);
    }

    //查询所有供应商  http://localhost:3000/api/product/supply-list
    @Autowired
    private SupplyServiceImpl supplyService;
    @GetMapping("/supply-list")
    public Result selectSupplyList(){
        List<Supply> supplies = supplyService.selectSupplyList();
        return Result.ok(supplies);
    }

    //查询所有商品的商品分类树   http://localhost:3000/api/product/category-tree
    @Autowired
    private ProductTypeServiceImpl productTypeService;
    @GetMapping("/category-tree")
    public Result selectAllTypeTree(){
        List<ProductType> productTypeTree = productTypeService.selectAllTypeTree();
        return Result.ok(productTypeTree);
    }

    //查询商品产地   http://localhost:3000/api/product/place-list
    @Autowired
    private PlaceServiceImpl placeService;
    @GetMapping("/place-list")
    public Result selectPlaces(){
        List<Place> places = placeService.selectAllPlaces();
        return Result.ok(places);
    }

    //查询商品单位   http://localhost:3000/api/product/unit-list
    @Autowired
    private UnitServiceImpl unitService;
    @GetMapping("/unit-list")
    public Result selectAllUnit(){
        List<Unit> units = unitService.selectAllUnit();
        return Result.ok(units);
    }

    //上传图片  http://localhost:9999/warehouse/product/img-upload
    @Value("${file.upload-path}")
    private String uploadPath;
    @RequestMapping("/img-upload")
    @CrossOrigin //表示/product/img-upload允许被跨域请求
    public Result uploadPicture(MultipartFile file){
        try {

            File uploadDirFile = ResourceUtils.getFile(uploadPath);  //拿到图片上传到的目录路径的File对象
            String absolutePath = uploadDirFile.getAbsolutePath();  //拿到图片上传到的目录路径的磁盘路径
            String originalFilename = file.getOriginalFilename();  //拿到上传的图片的名称
            String uploadFilePath = absolutePath+"\\"+originalFilename;
            file.transferTo(new File(uploadFilePath));   //上传图片
            return Result.ok("图片上传成功");
        } catch (Exception e) {
            return Result.err(Result.CODE_ERR_BUSINESS,"图片上传失败");
        }
    }

    //添加商品   http://localhost:3000/api/product/product-add
    @Value("${file.access-path}")
    private String imgPath;
    @Autowired
    private TokenUtils tokenUtils;
    @PostMapping("/product-add")
    public Result addProduct(@RequestBody Product product, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        product.setCreateBy(currentUser.getUserId());
        product.setImgs(imgPath+product.getImgs());   //添加上传图片的访问路径
        //step1：检查添加的商品是否与已有商品重复，要求商品名称和商品型号至少有一个要与已有商品不同
        Integer count = productService.selectAddProductIsExist(product);
        if (count>0){
            //如果要添加的商品已经存在
            return Result.err(Result.CODE_ERR_BUSINESS,"添加失败！商品已经存在");
        }
        //如果要添加的商品不存在
        Result result = productService.addProduct(product);
        return result;
    }


    //修改商品上下架状态  http://localhost:3000/api/product/state-change
    @RequestMapping("/state-change")
    public Result changeUpDownState(@RequestBody Product product){
        Result result = productService.changeUpDownState(product);
        return result;
    }

    //删除单个商品   http://localhost:3000/api/product/product-delete/7
    @RequestMapping("/product-delete/{productId}")
    public Result deleteProduct(@PathVariable Integer productId){
        List<Integer> productIds = new ArrayList<>();
        productIds.add(productId);
        //先查看商品是否上架，没上架的商品才能删除
        List<Product> products = productService.selectProductById(productIds);
        for (Product product:products){
            if (product.getUpDownState().equals("1")){
                return Result.err(Result.CODE_ERR_BUSINESS,"删除失败！不能删除已上架的商品...");
            }
        }
        //商品没有上架，可以删除
        Result result = productService.deleteProduct(productIds);
        return result;
    }

    //批量删除商品   http://localhost:3000/api/product/product-list-delete
    @RequestMapping("/product-list-delete")
    public Result deleteProducts(@RequestBody List<Integer> productIds){
        //先判断商品是否上架，没上架的商品才能删除
        List<Product> products = productService.selectProductById(productIds);
        for (Product product:products){
            if (product.getUpDownState().equals("1")){
                return Result.err(Result.CODE_ERR_BUSINESS,"删除失败！不能删除已上架的商品...");
            }
        }
        //商品没有上架，可以删除
        Result result = productService.deleteProduct(productIds);
        return result;
    }

    //修改产品信息   http://localhost:3000/api/product/product-update
    @RequestMapping("/product-update")
    public Result uodateProduct(@RequestBody Product product,@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        product.setUpdateBy(currentUser.getUserId());
        //step1:先查询修改后的product的product_name和product_num是否已经与某个已经存在的商品相同
        List<Product> products = productService.selectByNameAndNum(product);
        for (Product product1:products){
            if (product1!=null&&!product1.getProductId().equals(product.getProductId())){
                //根据条件查询到了响应的product并且id还不一样，说明正在修改的name和num与已经存在的某个商品一样了，不能修改
                return Result.err(Result.CODE_ERR_BUSINESS,"修改失败！修改后的商品已经存在...");
            }
        }
        //到这里说明可以修改了
        //判断图片是否修改过，检查图片属性的前缀是否包含/img/upload/即可
        if (!product.getImgs().contains(imgPath)){
            //图片修改过，给图片加上前缀即可
            product.setImgs(imgPath+product.getImgs());
        }
        //然后就可以进行修改了
        Result result = productService.updateProduct(product);
        return result;
    }
}
